package com.maxd.service.userMoney;


import com.maxd.model.UserMoney;
import com.maxd.respository.userMoney.UserMoneyJpaRepository;
import com.maxd.respository.userMoney.UserMoneyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 用户信誉分数明细
 */
@Service
public class UserMoneyServiceImpl implements UserMoneyService {

    /** 用户信誉分数明细 */
    @Autowired
    private UserMoneyJpaRepository userMoneyJpaRepository;
    /** 用户信誉分数明细自定义方法类 */
    @Autowired
    private UserMoneyRepository userMoneyRepository;
    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);


    @Override
    public UserMoney selectByUserId(Long userId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            UserMoney userMoney= userMoneyRepository.selectById(userId);
            if(userMoney==null){
                userMoney=new UserMoney();
                userMoney.setUserId(userId);
                userMoney.setMoney(0.00);
                userMoney.setCannotMoney(0.00);
                save(userMoney);
            }
            if(userMoney.getCannotMoney()==null){
                userMoneyRepository.updateCannotMoney(userId,0.00);
            }
            if(userMoney.getMoney()==null){
                userMoneyRepository.updateMoney(userId,0.00);
            }
            return userMoney;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return null;
    }

    @Override
    public Integer save(UserMoney userMoney) {
        userMoneyJpaRepository.save(userMoney);
        return 1;
    }

    /**
     *
     * @param type 操作方式 1是加 2是减
     * @param money 金额
     * @return
     */
    @Override
    public Integer updateMoney(int type,Long userId,Double money){
        //操作金额前先判断下是否有钱包
        UserMoney userMoney= userMoneyRepository.selectById(userId);
        if(userMoney==null){
            userMoney=new UserMoney();
            userMoney.setUserId(userId);
            userMoney.setMoney(0.00);
            userMoney.setCannotMoney(0.00);
            save(userMoney);
        }
        if(type==1){
            return userMoneyRepository.updateMoneyAdd(userId,money);
        }else{
            return userMoneyRepository.updateMoneySub(userId,money);
        }
    }

    @Override
    public Integer updateCannotMoneyTwo(Long userId,Double cannot_money) {
        return userMoneyRepository.updateMoneySubTwo(userId,cannot_money);
    }

    @Override
    public void updateMoneyById(Long userId, Double money) {
        userMoneyRepository.updateMoneyById(userId,money);
    }

}